package org.zxp.thread.volatileTest.singleton;

/**
 * @program: zxp-thread-test
 * @description: 懒汉模式的正确操作姿势
 * volatile的第二种用法：防止指令重排
 * @author: X-Pacific zhang
 * @create: 2019-05-10 17:46
 **/
public class LazySingleton {
    private volatile static LazySingleton lazySingleton = null;

    private LazySingleton(){
    }

    public static LazySingleton getInstance(){
        if(lazySingleton == null){
            try {
                //如果加上休眠则更严重（不能保证单例），为什么呢，休眠后在启动有CPU调度，不连续导致问题出现
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (LazySingletonill.class){
                if (lazySingleton == null) {
                    lazySingleton = new LazySingleton();
                }
            }
        }
        return lazySingleton;
    }

    public static void main(String[] args){
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                System.out.println(LazySingleton.getInstance().hashCode());
            }).start();
        }
    }
}
